Golang : Output or print out JSON stream/encoded data
Problem :
You need to produce JSON stream or JSON encoded data to web browser or client. How to do that?
Solution :
Set the header Content-Type
to application/json
and write the http.ResponseWriter.
For example :
package main
import (
"net/http"
)
func Employees(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// NOTE : put jsonStr in a FOR loop to read forever from database and encode the data with
// json.Marshal() function to produce JSON stream
// see https://www.socketloop.com/tutorials/golang-convert-csv-data-to-json-format-and-save-to-file
// for this example, we will use static JSON string
jsonStr := `[{"Name":"Dennis","Age":16,"Job":"CEO"},
{"Name":"Eva","Age":34,"Job":"CFO"},
{"Name":"Paul","Age":28,"Job":"COO"}]`
// output to web or client
w.Write([]byte(jsonStr))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", Employees)
http.ListenAndServe(":8080", mux)
}
Reference :
https://www.socketloop.com/tutorials/golang-unmarshal-json-from-http-response
See also : Golang : Unmarshal JSON from http response
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.1k Golang : Measure execution time for a function
+17.9k Golang : Simple client server example
+8.3k Golang : Implementing class(object-oriented programming style)
+11.5k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+9.4k Golang : Find the length of big.Int variable example
+7.9k Javascript : How to check a browser's Do Not Track status?
+6.5k Grep : How to grep for strings inside binary data
+14.8k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+4k Detect if Google Analytics and Developer Media are loaded properly or not
+18.5k Golang : Write file with io.WriteString
+22.7k Golang : Set and Get HTTP request headers example
+5.4k Golang : Return multiple values from function